package tls;

import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import java.security.Key;

public class RSAUtil {

    public static String encryptToHex(String text, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes());
        return  Hex.encodeHexString(encryptedBytes);
    }


    public static String decryptByHex(String hexStr, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes =  cipher.doFinal(Hex.decodeHex(hexStr));
        //cipher.doFinal(Base64.getDecoder().decode(encryptedText)); // 解码Base64字符串为字节数组
        return new String(decryptedBytes); // 将解密后的字节数组转换为字符串
    }


    public static byte[] decrypt(String hexStr, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes =  cipher.doFinal(Hex.decodeHex(hexStr));
        //cipher.doFinal(Base64.getDecoder().decode(encryptedText)); // 解码Base64字符串为字节数组
        return decryptedBytes;
    }
}
